package com.health.tools;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONObject;
import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

import com.blankj.utilcode.util.JsonUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.health.db.FDbManager;
import com.health.model.PeopleType;
import com.health.model.WebServiceData;
import com.health.model.WebServiceRootData;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.ARCHIVE_ENVIRONMENT;
import com.health.tablebean.ARCHIVE_FAMILYHISTORYINFO;
import com.health.tablebean.ARCHIVE_ILLNESSHISTORYINFO;
import com.health.tablebean.BD_DD_DRUG;
import com.health.tablebean.BD_DD_DRUG1;
import com.health.tablebean.BD_DD_INFO;
import com.health.tablebean.CD_DIABETESFOLLOWUP;
import com.health.tablebean.CD_DRUGCONDITION;
import com.health.tablebean.CD_HYPERTENSIONFOLLOWUP;
import com.health.tablebean.HD_PERSONAL_JKTZ;
import com.health.tablebean.PharmacyList;
import com.health.tablebean.webservice.BaseWebServiceBean;
import com.health.tablebean.webservice.Diabetes;
import com.health.tablebean.webservice.Hypertensio;
import com.health.tablebean.webservice.JiBing;
import com.health.tablebean.webservice.JiaZuShi;
import com.health.tablebean.webservice.Rollout;
import com.health.tablebean.webservice.ShouShu;
import com.health.tablebean.webservice.ShuXue;
import com.health.tablebean.webservice.WaiShang;
import com.health.tablebean.webservice.YiChuanBing;
import com.health.tablebean.webservice.ZhaiYao;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.settings.DataSynchronizationMainActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

//更新本机构及管理人员
//同步本机构用户
public class WebService implements OnWebServiceLinstener {
    // private static final String WSDL_URI =
    // "http://192.168.10.154:8081/ehr/webservice/getInfoByOrgUser";
    private static String WSDL_URI;
    private static String NAMESPACE;
    private static String METHOD_NAME;
    private ARCHIVE_BASEINFO mUserInfo;
    private Gson mGson = new Gson();
    private FDbManager mFdbm;
    private SoapObject mRequest;
    private SoapSerializationEnvelope mEnvelope;
    private OnWebServiceLinstener mLinstener;
    public int mSyncCount = 1;
    public int mDataSize = 0;
    private String orgid = "";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat sdf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Context mContext;
    private HashMap<String, Object> params;
    String SOAPACTION;
    private String responseData = "";
    private String downloadType;
    private String uploadType;

    public void setOnWebServiceLinstener(OnWebServiceLinstener linstener) {
        this.mLinstener = linstener;
    }

    public WebService(Context context) {
        mFdbm = FDbManager.getInstance(context);
        mContext = context;
    }

    /**
     * 同步数据
     * @param orgid
     * @throws Exception
     */
    public void synchrodata(String orgid) throws Exception {
        this.orgid = orgid;
        Log.e("orgid______________", orgid);
        WSDL_URI = GlobalConts.getUrlPost() + "webservice/ManageWebservice/getInfoByOrgUser";
        NAMESPACE = "http://webservice.yide.com/";
        METHOD_NAME = "getInfoByOrgUser";
        new Thread(synchroNetworkTask).start();
    }

    /**
     * 高血压数据下载（按创建人）
     *
     * @param orgid
     * @throws Exception
     */
    public void synchroGXYOrTNBdata(String orgid,String methodName) throws Exception {
        this.orgid = orgid;
        Log.e("orgid______________", orgid);
        METHOD_NAME = methodName;
        if ("getHyperByUserid".equals(methodName)){
            WSDL_URI = GlobalConts.getUrlPost() + "webservice/DownloadService/getHyperTenSionByOrgUser";
        }else{
            WSDL_URI = GlobalConts.getUrlPost() + "webservice/DownloadService/getTnbByOrgUser";
        }
        NAMESPACE = "http://webservice.yide.com/";
        new Thread(synchroGXYOrTNBTask).start();
    }

    /**
     * 药品库下载
     *
     * @throws Exception
     */
    public void synchroDrugsdata(String methodName) throws Exception {
        Log.e("methodName______", methodName);
        METHOD_NAME = methodName;
        WSDL_URI = GlobalConts.getUrlPost() + "webservice/DownloadService/"+methodName;

        NAMESPACE = "http://webservice.yide.com/";
        new Thread(synchroDrugsTask).start();
    }
    /**
     * 下载数据
     *
     * @param
     * @throws Exception
     */
    public void downloaddata(String serviceUrl, String methodName, String nameSpace, String soapAction,
                             HashMap<String, Object> params, String module) throws Exception {
        WSDL_URI = serviceUrl;
        NAMESPACE = nameSpace;
        METHOD_NAME = methodName;
        SOAPACTION = soapAction;
        this.params = params;
        this.downloadType = module;
        new Thread(downloadNetworkTask).start();
    }

    // public void uploaddata(List<BaseWebServiceBean> wshdatas, String method,
    // String valueKey) throws Exception {
    // this.wshdatas = wshdatas;
    // // http://192.168.10.146:8081/ehr/
    // WSDL_URI = "http://192.168.10.154:8080/ehr/" + "webservice/" + method;
    // this.valueKey = valueKey;
    // NAMESPACE = "http://webservice.zy.com/";
    // METHOD_NAME = "addHypertension";
    // new Thread(uploadNetworkTask).start();z
    // }
    public void uploaddata(String method, HashMap<String, Object> params, String module) throws Exception {

        WSDL_URI = GlobalConts.getUrlPost() + "webservice/UploadService/" + method;
        Log.e("上传地址：", WSDL_URI);
        NAMESPACE = "http://webservice.yide.com/";
        METHOD_NAME = method;
        this.params = params;
        this.uploadType = module;
        new Thread(uploadNetworkTask).start();
    }


    public void uploadFile(String method, String fileURL, String fileName, String modules, String cardNum, String type, String id) throws  Exception{
//        try {


        FileInputStream fis = new FileInputStream(fileURL);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = fis.read(buffer)) >= 0) {
            baos.write(buffer, 0, count);
        }
        String uploadBuffer = new String(Base64.encode(baos.toByteArray()));

        String namespace = "http://webservice.yide.com/";
        SoapObject soapObject = new SoapObject(namespace, method);
        soapObject.addProperty("name", fileName);  //参数1   图片名
        soapObject.addProperty("fileType", type);
        soapObject.addProperty("cardId", cardNum);
        soapObject.addProperty("type ", "png");
        soapObject.addProperty("id ", id);
        soapObject.addProperty("bytes", uploadBuffer);   //参数2  图片字符串

        Log.e("upPhoto-dddddd-",soapObject.toString());
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER10);
        Element[] header = new Element[1];
        header[0] = new Element().createElement("", "head");
        Element user = new Element().createElement("", "user");
        user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
//			Element module = new Element().createElement("", "module");
//			module.addChild(Node.TEXT, modules);
        Element token = new Element().createElement("", "token");
        token.addChild(Node.TEXT, SPUtil.getToken(mContext));

        header[0].addChild(Node.ELEMENT, user);
//			header[0].addChild(Node.ELEMENT, module);
        header[0].addChild(Node.ELEMENT, token);
        envelope.headerOut = header;


        envelope.bodyOut = mRequest;
        envelope.dotNet = false;
        envelope.setOutputSoapObject(soapObject);
        HttpTransportSE httpTranstation = new HttpTransportSE(GlobalConts.getUrlPost() + "webservice/" + method,60*1000*300);
        httpTranstation.call(namespace, envelope);
        SoapPrimitive response = (SoapPrimitive) envelope.getResponse();// 获得返回对象[]
        if (response != null) {
            String strres = response.toString();
            Log.e("strres", strres);
            complete(strres);// 数据上传完成
        }

//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 数据下载
     */
    Runnable downloadNetworkTask = new Runnable() {

        @Override
        public void run() {
            Looper.prepare();
            try {
                mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
                if (params != null && params.size() > 0) {
                    for (Entry<String, Object> item : params.entrySet()) {
                        mRequest.addProperty(item.getKey(), item.getValue().toString());
                    }
                }
                Element[] header = new Element[1];
                header[0] = new Element().createElement("", "head");
                Element user = new Element().createElement("", "user");
                user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                Element module = new Element().createElement("", "module");
                module.addChild(Node.TEXT, downloadType);
                Element token = new Element().createElement("", "token");
                token.addChild(Node.TEXT, SPUtil.getToken(mContext));

                header[0].addChild(Node.ELEMENT, user);
                header[0].addChild(Node.ELEMENT, module);
                header[0].addChild(Node.ELEMENT, token);
                mEnvelope.headerOut = header;
                /////

                mEnvelope.bodyOut = mRequest;
                mEnvelope.dotNet = false;
                HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI);
                start("正在下载数据...");
                httpTransportSE.call(null, mEnvelope);
                SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象
                Log.e("data--result:", "数据：" + response);
                if (response != null) {
                    String strres = response.toString();
                    complete(strres);
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                onError("IOException | XmlPullParserException" + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onError("Exception" + e.getMessage());
            }
        }
    };
    // Handler handler = new Handler() {
    // @Override
    // public void handleMessage(Message msg) {
    // super.handleMessage(msg);
    // Bundle data = msg.getData();
    // String val = data.getString("value");
    // Log.i("mylog", "请求结果为-->" + val);
    // // TODO
    // // UI界面的更新等相关操作
    // }
    // };

    /**
     * 上传高血压网络操作相关的子线程
     */
    Runnable uploadNetworkTask = new Runnable() {

        @Override
        public void run() {
            Looper.prepare();
            try {
                if (params != null && params.size() > 0) {
                    mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                    mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);

                    for (Entry<String, Object> item : params.entrySet()) {
                        mRequest.addProperty(item.getKey(), item.getValue().toString());
                    }

                    Element[] header = new Element[1];
                    header[0] = new Element().createElement("", "head");
                    Element user = new Element().createElement("", "user");
                    user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                    Element module = new Element().createElement("", "module");
                    module.addChild(Node.TEXT, uploadType);
                    Element token = new Element().createElement("", "token");
                    token.addChild(Node.TEXT, SPUtil.getToken(mContext));

                    header[0].addChild(Node.ELEMENT, user);
                    if (!TextUtils.isEmpty(uploadType)) {

                        header[0].addChild(Node.ELEMENT, module);
                    }
                    header[0].addChild(Node.ELEMENT, token);
                    mEnvelope.headerOut = header;
                    mEnvelope.bodyOut = mRequest;
                    mEnvelope.dotNet = false;
                    HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI, 1000 * 60 * 5);
                    start("正在上传数据...");
                    httpTransportSE.call(null, mEnvelope);
                    SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象[]
                    if (response != null) {
                        String strres = response.toString();
                        Log.e("strres", strres);
                        complete(strres);// 数据上传完成
                    }
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                onError("IOException | XmlPullParserException" + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onError("Exception" + e.getMessage());
            }

        }
    };

    /**
     * 数据同步网络操作相关的子线程
     */
    Runnable synchroNetworkTask = new Runnable() {

        @Override
        public void run() {
            Looper.prepare();
            try {
                mSyncCount = 1;
                mDataSize = 0;
//                int pageSize = 100;// 每页多少数据
//                int pageNumber = 1;// 第几页
                for (; ; ) {
                    mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                    mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
                    mRequest.addProperty("creater", orgid);
//                    Log.e("123321", orgid + "-----" + pageSize + "-------" + pageNumber);
                    Element[] header = new Element[1];
                    header[0] = new Element().createElement("", "head");
                    Element user = new Element().createElement("", "user");
                    user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                    Element token = new Element().createElement("", "token");
                    token.addChild(Node.TEXT, SPUtil.getToken(mContext));
                    header[0].addChild(Node.ELEMENT, user);
                    header[0].addChild(Node.ELEMENT, token);
                    mEnvelope.headerOut = header;

                    mEnvelope.bodyOut = mRequest;
                    mEnvelope.dotNet = false;
                    HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI, 1000 * 60 * 5);
                    Log.e("WSDL_URI", WSDL_URI);
                    Log.e("NAMESPACE", NAMESPACE);
                    Log.e("METHOD_NAME", METHOD_NAME);

                    start("正在获取数据...");
                    httpTransportSE.call(null, mEnvelope);

                    SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象
                    Log.e("response", response.toString());
                    if (response != null) {
                        String strres = response.toString();
//                        System.out.println("test" + "获取到第" + pageSize + "页数据,共" + pageNumber + "条");
//                        onSynchronize("获取到第" + pageNumber + "页数据,共" + pageSize + "条", mSyncCount, mDataSize);
                        if (mDataSize == 0) {
                            mDataSize = mGson.fromJson(strres, WebServiceRootData.class).getTotalSize();
                        }
                        if (synchroArchiveBaseInfo(strres,mDataSize,orgid) == mDataSize) {
                            complete("数据同步完成");
                            return;
                        }
                    }
//                    pageNumber += 1;
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                System.out.println("异常："+e.toString());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("异常："+e.toString());
            }
        }
    };

    /**
     * 数据同步网络操作相关的子线程
     */
    Runnable synchroGXYOrTNBTask = new Runnable() {

        @Override
        public void run() {
            Looper.prepare();
            try {
                mSyncCount = 1;
                mDataSize = 0;
                int pageSize = 100;// 每页多少数据
                int pageNumber = 1;// 第几页
                for (; ; ) {
                    mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                    mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
                    mRequest.addProperty("creater", orgid).addProperty("pageSize", pageSize).addProperty("pageNumber",
                            pageNumber);
                    Log.e("123321", orgid + "-----" + pageSize + "-------" + pageNumber);
                    Element[] header = new Element[1];
                    header[0] = new Element().createElement("", "head");
                    Element user = new Element().createElement("", "user");
                    user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                    Element token = new Element().createElement("", "token");
                    token.addChild(Node.TEXT, SPUtil.getToken(mContext));
                    header[0].addChild(Node.ELEMENT, user);
                    header[0].addChild(Node.ELEMENT, token);
                    mEnvelope.headerOut = header;

                    mEnvelope.bodyOut = mRequest;
                    mEnvelope.dotNet = false;
                    HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI, 1000 * 60 * 5);
                    Log.e("WSDL_URI", WSDL_URI);
                    Log.e("NAMESPACE", NAMESPACE);
                    Log.e("METHOD_NAME", METHOD_NAME);

                    start("正在获取数据...");
                    httpTransportSE.call(null, mEnvelope);

                    SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象
                    Log.e("response", response.toString());
                    if (response != null) {
                        String strres = response.toString();
                        System.out.println("test" + "获取到第" + pageSize + "页数据,共" + pageNumber + "条");
                        onSynchronize("获取到第" + pageNumber + "页数据,共" + pageSize + "条", mSyncCount, mDataSize);

                        if ("getHyperByUserid".equals(METHOD_NAME)){
                            if (synchroGXY(strres) < pageSize) {
                                complete("数据同步完成");
                                return;
                            }
                        }else  if ("getGlyByUserid".equals(METHOD_NAME)){
                            if (synchroTNB(strres) < pageSize) {
                                complete("数据同步完成");
                                return;
                            }
                        }
                    }
                    pageNumber += 1;
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                onError("IOException | XmlPullParserException" + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onError("Exception" + e.getMessage());
            }
        }
    };

    /**
     * @param json
     * @return 数据总数
     * @throws Exception
     */
    private int synchroArchiveBaseInfo(String json,int mDataSize,String creater) throws Exception {
        List<WebServiceData> datas = mGson.fromJson(json, WebServiceRootData.class).getData();

//        if (mDataSize == 0) {
//            mDataSize = mGson.fromJson(json, WebServiceRootData.class).getTotalSize();
//        }
        if (!datas.isEmpty()) {
            List<ARCHIVE_BASEINFO> locabs = null;
            for (WebServiceData data : datas) {
//                if(!data.getName().equals("王爱华")){
//                    continue;
//                }
                try {
                    System.out.println("人名："+data.getName());
                    System.out.println("正在同步第" + mSyncCount + "条数据" + "共" + mDataSize);
                    onSynchronize("正在同步第" + mSyncCount + "条数据", mSyncCount, mDataSize);
                    locabs = mFdbm.findAllByWhere(ARCHIVE_BASEINFO.class,
                            "idcard = '" + data.getCardid() + "'");
                    data.setCreater(creater);
                    if (locabs == null || locabs.isEmpty()) {
                         mFdbm.save(buildBaseInfo(data));


                    } else {
                        if (!TextUtils.isEmpty(data.getUpdatetime()) && locabs.get(0).getLAST_UPDATE_DATE() != null) {
                            if (!compare_date(locabs.get(0).getLAST_UPDATE_DATE(), data.getUpdatetime())) {
                               mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");

                            }

                        } else if (!TextUtils.isEmpty(data.getCreatetime()) && locabs.get(0).getLAST_UPDATE_DATE() != null) {
                            if (!compare_date(locabs.get(0).getLAST_UPDATE_DATE(), data.getCreatetime())) {
                               mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");

                            }

                        }else if(null == locabs.get(0).getLAST_UPDATE_DATE()){
                           mFdbm.updata(buildBaseInfo(data), "idcard = '" + data.getCardid() + "'");

                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    continue;
                }finally {
                    mSyncCount += 1;
                }

            }

        }
        return datas.size();
    }

    /**
     * 高血压数据解析
     * @param json
     * @return 数据总数
     * @throws Exception
     */
    private int synchroGXY(String json) throws Exception {
        if (mDataSize == 0) {
            mDataSize = mGson.fromJson(json, WebServiceRootData.class).getTotalSize();
        }
        JSONObject object = new JSONObject(json);
        String state = object.getString("state");
        String totalSize = object.getString("totalSize");
        if ("000".equals(state)) {
            JSONArray data = object.getJSONArray("data");
            if (data.length() > 0) {
                for (int i = 0; i < data.length(); i++) {
                    JSONObject obj = (JSONObject) data.get(i);
                    Gson gson = new Gson();
                    Hypertensio hypertensio = gson.fromJson(obj.toString(), Hypertensio.class);
                    CD_HYPERTENSIONFOLLOWUP gxy = new CD_HYPERTENSIONFOLLOWUP();
                    gxy.setWEIGHT(hypertensio.getAvoirdupois());
                    gxy.setIDCARD(hypertensio.getCardid());
                    gxy.setOBEYDOCTORBEHAVIOR(hypertensio.getCompiance());
                    gxy.setCREATEORG(hypertensio.getCreateorg());
                    gxy.setCREATER(hypertensio.getCreater());
                    gxy.setCREATED_BY(hypertensio.getCreater());
                    try {
                        if (!TextUtils.isEmpty(hypertensio.getCreatetime()))
                            gxy.setCREATED_DATE(GlobalConts.dateFormat.parse(hypertensio.getCreatetime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    gxy.setUPDATEORG(hypertensio.getUpdateorg());
                    try {
                        if (!TextUtils.isEmpty(hypertensio.getUpdatetime()))
                            gxy.setLAST_UPDATE_DATE(GlobalConts.dateFormat.parse(hypertensio.getUpdatetime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    gxy.setSYMPTOM(hypertensio.getCurSymptom());
                    gxy.setMEDICATIONCOMPLIANCE(hypertensio.getDependence());
                    gxy.setDAILYDRINKNUM(hypertensio.getDrink());
                    gxy.setADR_EX(hypertensio.getEffectsState());
                    try {
                        if (!TextUtils.isEmpty(hypertensio.getHappentime())) {
                            gxy.setFOLLOWUPDATE(GlobalConts.dateFormat.parse(hypertensio.getHappentime()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    gxy.setFOLLOWUPDOCTOR(hypertensio.getInputMan());
                    gxy.setPSYCHOADJUSTMENT(hypertensio.getMentality());
                    try {
                        if (!TextUtils.isEmpty(hypertensio.getNextVisitDate())) {
                            gxy.setNEXTFOLLOWUPDATE(GlobalConts.dateFormat.parse(hypertensio.getNextVisitDate()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    gxy.setPHYSICALSYMPTOMOTHER(hypertensio.getOtherPositive());
                    gxy.setSYMPTOMOTHER(hypertensio.getOtherSymptom());
                    gxy.setARCHIVEID(hypertensio.getPersonalid());
                    gxy.setBMI(hypertensio.getPhysique());
                    gxy.setHYPERTENSION(hypertensio.getPressureH());
                    gxy.setHYPOTENSION(hypertensio.getPressureL());
                    gxy.setHEARTRATE(hypertensio.getPulseRate());
                    gxy.setDAILYDRINKNUMTARGET(hypertensio.getTargetDrink());
                    Rollout rollout = hypertensio.getRollout();
                    if (rollout != null) {
                        gxy.setREFERRALREASON(TextUtils.isEmpty(rollout.getHpc()) ? "" : rollout.getHpc());
                        gxy.setREFERRALORG(TextUtils.isEmpty(rollout.getRollInRegion()) ? "" : rollout.getRollInRegion());
                    }
                    gxy.setEATSALTTYPE(hypertensio.getSalt());
                    gxy.setADR(hypertensio.getSideEffects());
                    gxy.setDAILYSMOKENUM(hypertensio.getSmoke());
                    gxy.setASSISTANTEXAM(hypertensio.getSubCheck());
                    gxy.setWEIGHTTARGET(hypertensio.getTargetAvoirdupois());
                    gxy.setBMITARGET(hypertensio.getTargetPhysique());
                    gxy.setEATSALTTARGET(hypertensio.getTargetSalt());
                    gxy.setDAILYSMOKENUMTARGET(hypertensio.getTargetSmoke());
                    gxy.setSPORTTIMESPERWEEKTARGET(hypertensio.getTargetTraining());
                    gxy.setSPORTPERMINUTESTIMETARGET(hypertensio.getTargetTrainingMin());
                    gxy.setSPORTTIMEPERWEEK(hypertensio.getTraining());
                    gxy.setSPORTPERMINUTETIME(hypertensio.getTrainingMin());
                    gxy.setFOLLOWUPTYPE(hypertensio.getVisitType());
                    if(!TextUtils.isEmpty(hypertensio.getToSalt())){
                        gxy.setTOSALT(hypertensio.getToSalt());
                    }else{
                        gxy.setTOSALT("");
                    }
                    if(!TextUtils.isEmpty(hypertensio.getIsReferral())){
                        gxy.setISREFERRAL(hypertensio.getIsReferral());
                    }else{
                        gxy.setISREFERRAL("DM01-11_1");
                    }

                    if(!TextUtils.isEmpty(hypertensio.getHealthAssess())){
                        gxy.setHEALTH_ASSESS(hypertensio.getHealthAssess());
                    }else{
                        gxy.setHEALTH_ASSESS("");
                    }

                    if (!TextUtils.isEmpty(hypertensio.getVisitWay())){
                        if (hypertensio.getVisitWay().contains("DM04-04")) {
                            Log.e("随诊方式1", hypertensio.getVisitWay());
                            gxy.setFOLLOWUPWAY(hypertensio.getVisitWay().replace("DM04-04", "DM04-15"));
                        } else {
                            gxy.setFOLLOWUPWAY(hypertensio.getVisitWay());
                            Log.e("随诊方式2", hypertensio.getVisitWay());
                        }
                    }
                    gxy.setHeight("");
                    onSynchronize("正在同步第" + mSyncCount + "条数据", mSyncCount, mDataSize);
                    List<ARCHIVE_BASEINFO> baseinfos = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,
                            "ARCHIVEID = '" + hypertensio.getPersonalid() + "'");
                    String idcard = "";
                    if (baseinfos!=null && baseinfos.size()>0){
                        idcard = baseinfos.get(0).getIDCARD();
                    }
                    List<CD_HYPERTENSIONFOLLOWUP> gxyList = NovaApplication.fdbmanger.findAllByWhere(CD_HYPERTENSIONFOLLOWUP.class,
                            "IDCARD = '" + idcard + "'");

                    if (gxyList.size() > 0) {
                        CD_HYPERTENSIONFOLLOWUP hypertensionfollowup = gxyList.get(0);
                        Date created_date_local = hypertensionfollowup.getCREATED_DATE();
                        Date last_update_date = hypertensionfollowup.getLAST_UPDATE_DATE();

                        //修改时间为空，未作修改，通过创建时间进行判断
                        if (TextUtils.isEmpty(hypertensio.getUpdatetime())) {
                            //本地修改时间大于服务器创建时间， 不需要修改本地高血压随访数据
                            if (!TextUtils.isEmpty(hypertensio.getCreatetime())) {
                                if (compare_date(last_update_date, hypertensio.getCreatetime())) {

                                } else {
                                    //本地创建时间小于服务器创建时间，修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                    deleteOldDrugData(idcard);
                                    List<PharmacyList> pharmacyList = hypertensio.getPharmacyList();
                                    saveDrug(pharmacyList, "1",idcard);
                                    NovaApplication.fdbmanger.updata(gxy, "IDCARD='" + idcard + "'");
                                }
                            }

                        } else {
                            //修改时间不为空，已经修改，通过修改时间进行判断（代码确定本地修改时间一定存在）
                            if (compare_date(last_update_date, hypertensio.getUpdatetime())) {
                                //本地修改时间大于服务器修改时间， 不需要修改本地高血压随访数据

                            } else {
                                //本地修改时间小于服务器修改时间， 修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                deleteOldDrugData(idcard);
                                List<PharmacyList> pharmacyList = hypertensio.getPharmacyList();
                                saveDrug(pharmacyList, "1",idcard);
                                NovaApplication.fdbmanger.updata(gxy, "IDCARD='" + idcard + "'");
                            }
                        }
                    } else {
                        //没有此人的数据直接进行保存
                        deleteOldDrugData(idcard);
                        List<PharmacyList> pharmacyList = hypertensio.getPharmacyList();
                        saveDrug(pharmacyList, "1",idcard);
                        NovaApplication.fdbmanger.save(gxy);
                    }
                    mSyncCount += 1;
                }
            }
        } else if ("001".equals(state)) {
            Toast.makeText(mContext, "创建机构为空", Toast.LENGTH_SHORT).show();
        } else if ("002".equals(state)) {
            Toast.makeText(mContext, "查询异常", Toast.LENGTH_SHORT).show();
        } else if ("003".equals(state)) {
            Toast.makeText(mContext, "没有查到相关数据", Toast.LENGTH_SHORT).show();
        }
        return Integer.parseInt(totalSize);
    }


    /**
     * 糖尿病数据解析
     * @param json
     * @return
     */
    private int synchroTNB(String json) throws Exception{
        if (mDataSize == 0) {
            mDataSize = mGson.fromJson(json, WebServiceRootData.class).getTotalSize();
        }
        JSONObject object = new JSONObject(json);
        String state = object.getString("state");
        String totalSize = object.getString("totalSize");
        if ("000".equals(state)) {
            JSONArray data = object.getJSONArray("data");
            if (data.length() > 0) {
                for (int i = 0; i < data.length(); i++) {
                    JSONObject obj = (JSONObject) data.get(i);
                    Gson gson = new Gson();
                    Diabetes diabetes = gson.fromJson(obj.toString(), Diabetes.class);
                    CD_DIABETESFOLLOWUP tnb = new CD_DIABETESFOLLOWUP();
                    tnb.setDORSALISPEDISPULSE(diabetes.getArteriopalmus());
                    tnb.setWEIGHT(diabetes.getAvoirdupois());
                    tnb.setIDCARD(diabetes.getCardid());
                    tnb.setOBEYDOCTORBEHAVIOR(diabetes.getCompiance());
                    tnb.setCREATEORG(diabetes.getCreateorg());
                    tnb.setCREATER(diabetes.getCreater());
                    tnb.setCREATED_BY(diabetes.getCreater());
                    try {
                        tnb.setCREATED_DATE(GlobalConts.dateFormat.parse(diabetes.getCreatetime()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    tnb.setUPDATEORG(diabetes.getUpdateorg());

                    try {
                        if (!TextUtils.isEmpty(diabetes.getHappentime())) {
                            tnb.setFOLLOWUP_DATE(GlobalConts.dateFormat.parse(diabetes.getHappentime()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    tnb.setMEDICATIONCOMPLIANCE(diabetes.getDependence());
                    tnb.setDAILYDRINKNUM(diabetes.getDrink());
                    tnb.setADR(diabetes.getSideEffects());
                    tnb.setADR_EX(diabetes.getEffectsState());
                    tnb.setFPG(diabetes.getFbg());
                    tnb.setHBALC(diabetes.getHgb());
                    tnb.setFOLLOWUPDOCTOR(diabetes.getInputMan());
                    tnb.setINSULINUSAGE(diabetes.getInsulinDose());
                    tnb.setINSULINTYPE(diabetes.getInsulinType());
                    tnb.setHYPOGLYCEMIARREACTION(diabetes.getLowEffects());
                    tnb.setPSYCHOADJUSTMENT(diabetes.getMentality());
                    try {
                        if (!TextUtils.isEmpty(diabetes.getNextVisitDate())) {
                            tnb.setNEXTFOLLOWUP_DATE(GlobalConts.dateFormat.parse(diabetes.getNextVisitDate()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    tnb.setPHYSICALSYMPTOMOTHER(diabetes.getOtherPositive());
                    tnb.setSYMPTOMOTHER(diabetes.getOtherSymptom());
                    tnb.setARCHIVEID(diabetes.getPersonalid());
                    tnb.setSYMPTOM(diabetes.getCurSymptom());
                    tnb.setBMI(diabetes.getPhysique());
                    tnb.setHYPERTENSION(diabetes.getPressureH());
                    tnb.setHYPOTENSION(diabetes.getPressureL());
                    if(!TextUtils.isEmpty(diabetes.getIsReferral())){
                        tnb.setISREFERRAL(diabetes.getIsReferral());
                    }else{
                        tnb.setISREFERRAL("DM01-11_1");
                    }

                    if(!TextUtils.isEmpty(diabetes.getHealthAssess())){
                        tnb.setHEALTH_ASSESS(diabetes.getHealthAssess());
                    }else{
                        tnb.setHEALTH_ASSESS("");
                    }
                    if (!TextUtils.isEmpty(diabetes.getRes2())){
                        if (!TextUtils.isEmpty(diabetes.getHappentime())){
                            String[] split = diabetes.getHappentime().split("-");
                            try {
                                tnb.setEXAMDATE(GlobalConts.dateFormat.parse(split[0] + "-"+diabetes.getRes2() + "-" + diabetes.getRes3()));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    tnb.setDORSALISPEDISPULSE_Less(diabetes.getRes5());
                    tnb.setDORSALISPEDISPULSE_Disa(diabetes.getRes6());
                    tnb.setSTAPLEFOODDAILYG(diabetes.getRice());
                    tnb.setDAILYSMOKENUM(diabetes.getSmoke());
                    tnb.setASSISTANTEXAM(diabetes.getSubCheck());
                    tnb.setWEIGHTTARGET(diabetes.getTargetAvoirdupois());
                    tnb.setDAILYDRINKNUMTARGET(diabetes.getTargetDrink());
                    tnb.setBMITARGET(diabetes.getTargetPhysique());
                    tnb.setSTAPLEFOODDAILYGTARGET(diabetes.getTargetRice());
                    tnb.setDAILYSMOKENUMTARGET(diabetes.getTargetSmoke());
                    tnb.setSPORTTIMESPERWEEKTARGET(diabetes.getTargetTraining());
                    tnb.setSPORTPERMINUTESTIMETARGET(diabetes.getTargetTrainingMin());
                    tnb.setSPORTTIMEPERWEEK(diabetes.getTraining());
                    tnb.setSPORTPERMINUTETIME(diabetes.getTrainingMin());
                    tnb.setFOLLOWUPTYPE(diabetes.getVisitType());
                    if (!TextUtils.isEmpty(diabetes.getVisitWay())){
                        if (diabetes.getVisitWay().contains("DM04-04")){
                            tnb.setFOLLOWUPWAY(diabetes.getVisitWay().replace("DM04-04","DM04-15"));
                        }else{
                            tnb.setFOLLOWUPWAY(diabetes.getVisitWay());
                        }
                    }
                    try {
                        if (!TextUtils.isEmpty(diabetes.getUpdatetime())) {
                            tnb.setLAST_UPDATE_DATE(GlobalConts.dateFormat.parse(diabetes.getUpdatetime()));
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    Diabetes.Rolloutrollout rollout = diabetes.getRollout();
                    if (rollout != null) {
                        tnb.setREFERRALREASON(TextUtils.isEmpty(rollout.getHpc()) ? "" : rollout.getHpc());
                        tnb.setREFERRALORG(TextUtils.isEmpty(rollout.getRollInRegion()) ? "" : rollout.getRollInRegion());
                    }
                    onSynchronize("正在同步第" + mSyncCount + "条数据", mSyncCount, mDataSize);
                    List<ARCHIVE_BASEINFO> baseinfos = NovaApplication.fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class,
                            "ARCHIVEID = '" + diabetes.getPersonalid() + "'");
                    String idcard = "";
                    if (baseinfos!=null && baseinfos.size()>0){
                        idcard = baseinfos.get(0).getIDCARD();
                    }
                    List<CD_DIABETESFOLLOWUP> tnbList = NovaApplication.fdbmanger.findAllByWhere(CD_DIABETESFOLLOWUP.class,
                            "IDCARD='" + idcard + "'");

                    if (tnbList.size() > 0) {
                        CD_DIABETESFOLLOWUP diabetesfollowup = tnbList.get(0);
                        Date created_date_local = diabetesfollowup.getCREATED_DATE();
                        Date last_update_date = diabetesfollowup.getLAST_UPDATE_DATE();

                        //修改时间为空，未作修改，通过创建时间进行判断
                        if (TextUtils.isEmpty(diabetes.getUpdatetime())) {
                            //本地创建时间大于服务器创建时间， 不需要修改本地高血压随访数据
                            if (!TextUtils.isEmpty(diabetes.getCreatetime())) {
                                if (compare_date(created_date_local, diabetes.getCreatetime())) {
                                } else {
                                    //本地创建时间小于服务器创建时间，修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                    deleteOldDrugData(idcard);
                                    List<PharmacyList> pharmacyList = diabetes.getPharmacyList();
                                    saveDrug(pharmacyList, "2",idcard);
                                    NovaApplication.fdbmanger.updata(tnb, "IDCARD='" + idcard + "'");
                                }
                            }

                        } else {
                            //修改时间不为空，已经修改，通过修改时间进行判断（代码确定本地修改时间一定存在）
                            if (compare_date(last_update_date, diabetes.getUpdatetime())) {
                                //本地修改时间大于服务器修改时间， 不需要修改本地高血压随访数据
                            } else {
                                //本地修改时间小于服务器修改时间， 修改本地高血压随访数据，并且删除本人的所有药物数据重新存储
                                deleteOldDrugData(idcard);
                                List<PharmacyList> pharmacyList = diabetes.getPharmacyList();
                                saveDrug(pharmacyList, "2",idcard);
                                NovaApplication.fdbmanger.updata(tnb, "IDCARD='" + idcard + "'");
                            }
                        }
                    } else {
                        //没有此人的数据直接进行保存
                        deleteOldDrugData(idcard);
                        List<PharmacyList> pharmacyList = diabetes.getPharmacyList();
                        saveDrug(pharmacyList, "2",idcard);
                        NovaApplication.fdbmanger.save(tnb);
                    }
                    mSyncCount += 1;
                }
            }
        } else if ("001".equals(state)) {
            Toast.makeText(mContext, "创建机构为空", Toast.LENGTH_SHORT).show();
        } else if ("002".equals(state)) {
            Toast.makeText(mContext, "查询异常", Toast.LENGTH_SHORT).show();
        } else if ("003".equals(state)) {
            Toast.makeText(mContext, "没有查到相关数据", Toast.LENGTH_SHORT).show();
        }
        return Integer.parseInt(totalSize);
    }

    /**
     * 数据同步网络操作相关的子线程
     */
    Runnable synchroDrugsTask = new Runnable() {

        @Override
        public void run() {
            Looper.prepare();
            try {
                mSyncCount = 1;
                mDataSize = 0;
//                int pageSize = 100;// 每页多少数据
//                int pageNumber = 1;// 第几页
                for (; ; ) {
                    mRequest = new SoapObject(NAMESPACE, METHOD_NAME);
                    mEnvelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER10);
//                    mRequest.addProperty("creater", orgid).addProperty("pageSize", pageSize).addProperty("pageNumber",
//                            pageNumber);
//                    Log.e("123321", orgid + "-----" + pageSize + "-------" + pageNumber);
                    Element[] header = new Element[1];
                    header[0] = new Element().createElement("", "head");
                    Element user = new Element().createElement("", "user");
                    user.addChild(Node.TEXT, SPUtil.getRegisterImei(mContext));
                    Element token = new Element().createElement("", "token");
                    token.addChild(Node.TEXT, SPUtil.getToken(mContext));
                    header[0].addChild(Node.ELEMENT, user);
                    header[0].addChild(Node.ELEMENT, token);
                    mEnvelope.headerOut = header;

                    mEnvelope.bodyOut = mRequest;
                    mEnvelope.dotNet = false;
                    HttpTransportSE httpTransportSE = new HttpTransportSE(WSDL_URI, 1000 * 60 * 5);
                    Log.e("WSDL_URI", WSDL_URI);
                    Log.e("NAMESPACE", NAMESPACE);
                    Log.e("METHOD_NAME", METHOD_NAME);

                    start("正在获取数据...");
                    httpTransportSE.call(null, mEnvelope);

                    SoapPrimitive response = (SoapPrimitive) mEnvelope.getResponse();// 获得返回对象
                    Log.e("response", response.toString());

                    if (response != null) {
                        String strres = response.toString();
                        String data = JsonUtils.getString(strres,"data");
                        if (mDataSize == 0) {
                            mDataSize = JsonUtils.getInt(strres,"totalSize");
                        }
                        if (synchroDrug(data,mDataSize) == mDataSize) {
                            complete("数据同步完成");
                            return;
                        }

                    }
                }
            } catch (IOException | XmlPullParserException e) {
                e.printStackTrace();
                onError("IOException | XmlPullParserException" + e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                onError("Exception" + e.getMessage());
            }
        }
    };

    /**
     * @param json
     * @return 数据总数
     * @throws Exception
     */
    private int synchroDrug(String json,int mDataSize) throws Exception {

        List<BD_DD_DRUG1> datas = mGson.fromJson(json,new TypeToken<List<BD_DD_DRUG1>>() {}.getType());
//        List<BD_DD_DRUG> datas = mGson.fromJson(json,new TypeToken<List<BD_DD_DRUG>>() {}.getType());

        if (!datas.isEmpty()) {
            mFdbm.deleteAllInfo(BD_DD_DRUG.class);
//            List<BD_DD_DRUG> locabs = null;
            for (BD_DD_DRUG1 data : datas) {
                BD_DD_DRUG bd_dd_drug = new BD_DD_DRUG();
                bd_dd_drug.setId(data.getId());
                bd_dd_drug.setDrugs(data.getDrugs());
                bd_dd_drug.setAbbreviation(data.getAbbreviation());
                bd_dd_drug.setDosage(data.getDosage());
                bd_dd_drug.setRes1(data.getRes1());
                bd_dd_drug.setRes2(data.getRes2());
                bd_dd_drug.setRes3(data.getRes3());
                bd_dd_drug.setTjdosage(data.getTjDosage());
                bd_dd_drug.setTjdrugname(data.getTjDrugName());
                bd_dd_drug.setTjmcjl(data.getTjMcjl());
                bd_dd_drug.setTjyongfa(data.getTjYongfa());
                bd_dd_drug.setUsage(data.getYongfa());
                bd_dd_drug.setType(data.getType().replace("drug_",""));
                bd_dd_drug.setProname(data.getProName());
                bd_dd_drug.setTjproname(data.getTjproname());
                System.out.println("药品名称："+data.getDrugs());
                System.out.println("正在同步第" + mSyncCount + "条数据" + "共" + mDataSize);
                onSynchronize("正在同步第" + mSyncCount + "条数据", mSyncCount, mDataSize);
//                locabs = mFdbm.findAllByWhereInInfoDB(BD_DD_DRUG.class,
//                        "drugs = '" + data.getDrugs() + "'");
                mFdbm.saveInInfoDB(bd_dd_drug);
//                if (locabs == null || locabs.isEmpty()) {
//                    mFdbm.saveInInfoDB(data);
//                } else {
//                    if (!TextUtils.isEmpty(data.getDrugs())) {
//                        mFdbm.updataInInfoDB(data, "drugs = '" + data.getDrugs() + "'");
//
//                    }
//                }
                mSyncCount += 1;
            }

        }
        return datas.size();
    }

    /**
     * 比较两个时间的大小，dt1大于DATE2，返回true，否则返回false
     *
     * @param dt1
     * @param DATE2
     * @return
     */
    public boolean compare_date(Date dt1, String DATE2) {

        try {
            if (DATE2.length() > 10) {
                Date dt2 = sdf_time.parse(DATE2);
                if (!(dt1.getTime() < dt2.getTime())) {
                    return true;
                } else {
                    return false;
                }
            } else {
                Date dt2 = sdf.parse(DATE2);
                if (dt1.getTime() > dt2.getTime()) {
                    return true;
                } else {
                    return false;
                }
            }

        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

    private ARCHIVE_BASEINFO buildBaseInfo(WebServiceData data) throws ParseException, Exception {
        if (data == null) {
            throw new Exception("WebService.buildData(Data data) ::data not null");
        }
        // System.out.println(data.getDELFLAG);
        // System.out.println(data.getDelflag());
        ARCHIVE_BASEINFO userInfo = new ARCHIVE_BASEINFO();

        userInfo.setARCHIVEID(data.getPersonalid());
        userInfo.setSEX(data.getSex());
        System.out.println("建档日期："+data.getHappentime());


        userInfo.setADDR(data.getAddress());
        userInfo.setHOUSEHOLD_ADDR(data.getGbname());
        if (!TextUtils.isEmpty(data.getBirthday())) {
//            userInfo.setBIRTHDAY(sdf.parse(data.getBirthday()));
            userInfo.setBIRTHDAY(sdf.parse(data.getBirthday()));
        }
        userInfo.setCUSTOMERNAME(data.getName());
        userInfo.setNATION(data.getNation());
        userInfo.setMINORITY(minzuName(data.getNation()));
        userInfo.setPHONE(data.getMobile());
        userInfo.setDOCTOR(data.getDutyDoctor());
        userInfo.setIDCARD(data.getCardid());

        // 行政信息
        userInfo.setPROVINCE(data.getProvince());
        userInfo.setCITY(data.getCity());
        userInfo.setCOUNTY(data.getCounty());
        userInfo.setSTREET(data.getStreet());
        userInfo.setCOMMITTEE(data.getCommittee());
        userInfo.setUPDATEORG(data.getUpdateorg());
        // userInfo.setTOWNNAME(data.gettOWNNAME);
        // userInfo.setVILLAGENAME(data.getIdcardVas());
        // userInfo.setTOWNNAME(sp.getString("str_xz", ""));
        // userInfo.setVILLAGENAME(sp.getString("str_cz", ""));
        userInfo.setTOWNNAME(SPUtil.getstr_xz(mContext));
        userInfo.setVILLAGENAME(SPUtil.getstr_cz(mContext));
        // 创建信息
        userInfo.setCARDTYPE(data.getCardtype());
        userInfo.setCREATER(data.getCreater());
//        if (!TextUtils.isEmpty(data.getCreatetime())) {
//            if (data.getCreatetime().length() > 10) {
//                userInfo.setCREATED_DATE(sdf_time.parse(data.getCreatetime()));
//            } else {
//                userInfo.setCREATED_DATE(sdf.parse(data.getCreatetime()));
//            }
//        }
        if (null != data.getHappentime()) {
            userInfo.setCREATED_DATE(data.getHappentime());
        }else{
            userInfo.setCREATED_DATE("");
        }
        userInfo.setCREATED_BY(data.getCreater());
        userInfo.setCREATEORG(data.getCreateorg());
        // userInfo.setCREATEUNIT(data.getCreateorg());
        userInfo.setCREATEUNIT_NAME(SPUtil.getstr_jddw(mContext));
        // userInfo.setCREATEMEN_NAME(data.getCreater());
        // userInfo.setCUSTOMERID(data.getid);
        if (TextUtils.isEmpty(data.getModified())) {
            userInfo.setMODIFIED(data.getCreater());
        } else {
            userInfo.setMODIFIED(data.getModified());
        }

        if(data.getCardid() == null || data.getCardid().equals("")){
            data.setCardid("");
        }

        String year = "";
        int age = 0;
        Calendar c = Calendar.getInstance();
        if (data.getCardid().length() < 11) {

        } else {
            if(data.getCardid().length() == 18){
                year = data.getCardid().substring(6, 10);
            }else if(data.getCardid().length() ==15){
                year = "19"+data.getCardid().substring(6, 8);
            }else{
                year = "2019";
            }

        }

        try {
            age = GlobalConts.getAge(sdf.parse(data.getBirthday()));
            if(age >= 100 || age < 1){
                age = c.get(Calendar.YEAR) - Integer.parseInt(year);
            }
//            if(Integer.parseInt(year) > c.get(Calendar.YEAR)){
//                age = GlobalConts.getAge(sdf.parse(data.getBirthday()));
//            }
//            if(data.getCardid().length() != 18 && data.getCardid().length() != 15){
//                age = GlobalConts.getAge(sdf.parse(data.getBirthday()));
//            }
//            if(null != data.getBirthday() && !data.getBirthday().equals("")) {
//                age = GlobalConts.getAge(sdf_time.parse(data.getBirthday()));
//            }
        } catch (Exception e) {
            age = 40;
        }

        if (age >= 65) {
            String population = PeopleType.OLD;
            if (!TextUtils.isEmpty(userInfo.getPOPULATION_TYPE())) {
                if (population.equals(PeopleType.YBRQ)) {

                }
                String pop = userInfo.getPOPULATION_TYPE();
                String[] pops = pop.split(",");
                if (!Arrays.asList(pops).contains(population)) {
                    pop = pop + "," + population;
                    userInfo.setPOPULATION_TYPE(pop);
                }
            } else {
                userInfo.setPOPULATION_TYPE(population);
            }
        } else if ( age <= 6){
            String population = PeopleType.CHILD;
            if (!TextUtils.isEmpty(userInfo.getPOPULATION_TYPE())) {
                if (population.equals(PeopleType.YBRQ)) {

                }
                String pop = userInfo.getPOPULATION_TYPE();
                String[] pops = pop.split(",");
                if (!Arrays.asList(pops).contains(population)) {
                    pop = pop + "," + population;
                    userInfo.setPOPULATION_TYPE(pop);
                }
            } else {
                userInfo.setPOPULATION_TYPE(population);
            }
        }else {
            userInfo.setPOPULATION_TYPE(PeopleType.YBRQ);
        }
//        String pType = calcPopulation(data);
//        System.out.println("患者人："+pType+"--"+data.getName());
//        userInfo.setPOPULATION_TYPE(pType);

        if (!TextUtils.isEmpty(data.getUpdatetime())) {
            if (data.getUpdatetime().length() > 10) {
                userInfo.setLAST_UPDATE_DATE(sdf_time.parse(data.getUpdatetime()));
            } else {
                userInfo.setLAST_UPDATE_DATE(sdf.parse(data.getUpdatetime()));
            }
        }

        if (TextUtils.isEmpty(data.getModified())) {
            userInfo.setLAST_UPDATE_BY(data.getCreater());
        } else {
            userInfo.setLAST_UPDATE_BY(data.getModified());
        }

        userInfo.setCULTURE(data.getEducation());
        userInfo.setJOB(data.getOccupation());
        userInfo.setMARITALSTATUS(data.getMarriage());
        userInfo.setBLOODTYPE(data.getBloodType());
        userInfo.setLIVETYPE(data.getDomicileType());
        userInfo.setMEDICALPAYTYPE(data.getPaymentMode()); // 医疗支付方式
        userInfo.setMEDICALPAYTYPE_OTHER(data.getRes7());
        userInfo.setPILLALLERGIC(data.getYwgms());// 药物过敏史
        userInfo.setEXPOSURE(data.getYwbls());// 有无暴露史
        userInfo.setWORKUNIT(data.getUnitName());// 工作单位
        userInfo.setCONTACTNAME(data.getLinkmanName());// 联系人姓名
        userInfo.setCONTACTPHONE(data.getLinkmanPhone());// 联系人电话
        userInfo.setRH(data.getRh());
        ZhaiYao zhaiyao = data.getZhaiyao();
        if(zhaiyao!=null){
            userInfo.setPILLALLERGIC(zhaiyao.getAllergicSource());
            userInfo.setPILLALLERGIC_OTHER(zhaiyao.getAllergicOther());
            userInfo.setEXPOSURE(zhaiyao.getRes9());
            userInfo.setDISEASENDITION(zhaiyao.getDisability());
            userInfo.setDISEASENDITION_EX(zhaiyao.getDisabilityOther());
        }

        userInfo.setDISEASE(data.getYcbs());// 遗传病史

        userInfo.setDISTRICT_ID(data.getSignCondition());
        userInfo.setISMATERIALS(data.getIsMaterials());
        userInfo.setISPROVERTY(data.getIsProverty());
        List<ShouShu> ss = data.getSs();//手术
        List<WaiShang> wais = data.getWais();//外伤
        List<ShuXue> shux = data.getShux();//输血
        List<JiBing> jbs = data.getJb();//疾病

        YiChuanBing yichuanbing = data.getYichuanbing();
        if (yichuanbing != null) {
            userInfo.setDISEASE_EX(yichuanbing.getHeredityhistory());//遗传病
        }

        List<ARCHIVE_ILLNESSHISTORYINFO> oldList = mFdbm.findAllByWhere(ARCHIVE_ILLNESSHISTORYINFO.class, "IDCARD = " + "'" + data.getCardid() + "'");
        if (oldList.size() > 0) {
            for (ARCHIVE_ILLNESSHISTORYINFO illnesshistoryinfo : oldList) {
                mFdbm.delete(illnesshistoryinfo);
            }
        }

        if (jbs != null && jbs.size() > 0) {
            for (JiBing jb : jbs) {
                if (jb != null) {
                    String formerlyType = jb.getFormerlyType();
                    if (!TextUtils.isEmpty(formerlyType)) {
                        String[] split = formerlyType.split(",");
                        for (int i = 0; i < split.length; i++) {
                            try {
                                ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                                if ("DM99-01_2".equals(split[i])) {
                                    JBRQData.saveJBLX(PeopleType.GXY, userInfo);
                                } else if ("DM99-01_3".equals(split[i])) {
                                    System.out.println("糖尿病患者："+userInfo.getCUSTOMERNAME());
                                    JBRQData.saveJBLX(PeopleType.TNB, userInfo);
                                } else if ("DM99-01_4".equals(split[i])) {
                                    JBRQData.saveJBLX(PeopleType.GXB, userInfo);
                                } else if ("DM99-01_7".equals(split[i])) {
                                    JBRQData.saveJBLX(PeopleType.NCZ, userInfo);
                                } else if ("DM99-01_8".equals(split[i])) {
                                    JBRQData.saveJBLX(PeopleType.JSB, userInfo);
                                } else if ("DM99-01_9".equals(split[i])) {
                                    JBRQData.saveJBLX(PeopleType.FJH, userInfo);
                                }

                                history.setILLNESSNAME_OTHER(jb.getDiseaseOther());
                                if (!TextUtils.isEmpty(jb.getAskDate())) {
                                    if(jb.getAskDate().length()==7){
                                        jb.setAskDate(jb.getAskDate()+"-01");
                                    }
                                    System.out.println("Giao:"+GlobalConts.dateFormat.parse(jb.getAskDate())+"---"+jb.getAskDate());

                                    history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(jb.getAskDate()));
                                }
                                history.setILLNESSTYPE("1");
                                history.setILLNESSNAME(split[i]);
                                history.setTHERIOMA(jb.getCancer());
                                history.setJOBILLNESS(jb.getIndustrialDisease());
                                history.setILLNESS_OTHER(jb.getDiseaseOther());
                                history.setIDCARD(data.getCardid());
                                mFdbm.save(history);
                            }catch (Exception e){
                                e.printStackTrace();
                                continue;
                            }

                        }
                    }
                }
            }
        }

        if (ss != null && ss.size() > 0) {
            for (ShouShu s : ss) {
                if (s != null) {
                    try {
                        ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                        history.setILLNESSNAME_OTHER(s.getOpsName());
                        if (!TextUtils.isEmpty(s.getOpsDate())) {
                            history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(s.getOpsDate()));
                        }
                        history.setILLNESSTYPE("2");
                        history.setIDCARD(data.getCardid());
                        mFdbm.save(history);
                    }catch (Exception e){
                        e.printStackTrace();
                        continue;
                    }

                }

            }
        }


        if (wais != null && wais.size() > 0) {
            for (WaiShang ws : wais) {
                if (ws != null) {
                    ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                    history.setILLNESSNAME_OTHER(ws.getCutPart());
                    if (!TextUtils.isEmpty(ws.getCutDate())) {
                        history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(ws.getCutDate()));
                    }
                    history.setILLNESSTYPE("3");
                    history.setIDCARD(data.getCardid());
                    mFdbm.save(history);
                }

            }
        }


        if (shux != null && shux.size() > 0) {
            for (ShuXue sx : shux) {
                if (sx != null) {
                    ARCHIVE_ILLNESSHISTORYINFO history = new ARCHIVE_ILLNESSHISTORYINFO();
                    history.setILLNESSNAME_OTHER(sx.getBloodReason());
                    if (!TextUtils.isEmpty(sx.getBloodDate())) {
                        history.setDIAGNOSETIME(GlobalConts.dateFormat.parse(sx.getBloodDate()));
                    }
                    history.setILLNESSTYPE("4");
                    history.setIDCARD(data.getCardid());
                    mFdbm.save(history);
                }

            }
        }

        List<ARCHIVE_FAMILYHISTORYINFO> historys = mFdbm.findAllByWhere(ARCHIVE_FAMILYHISTORYINFO.class,
                "IDCARD = '" + data.getCardid() + "'");
        if (historys.size() > 0) {
            for (ARCHIVE_FAMILYHISTORYINFO his : historys) {
                mFdbm.delete(his);
            }
        }

        List<JiaZuShi> jiazs = data.getJiazs();
        if (jiazs != null && jiazs.size() > 0) {
            ARCHIVE_FAMILYHISTORYINFO history = new ARCHIVE_FAMILYHISTORYINFO();
            for (int i = 0; i < jiazs.size(); i++) {
                if (jiazs.get(i) != null) {
                    if ("DM01-06_5_51".equals(jiazs.get(i).getRelation())) {
                        history.setFATHERHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setFATHERHISTORY_OTHER(jiazs.get(i).getReg0());
                    } else if ("DM01-06_5_52".equals(jiazs.get(i).getRelation())) {
                        history.setMOTHERHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setMOTHERHISTORY_OTHER(jiazs.get(i).getReg0());
                    } else if ("DM01-06_7".equals(jiazs.get(i).getRelation())) {
                        history.setBROTHERSISTERHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setBROTHERSISTERHISTORY_OTHER(jiazs.get(i).getReg0());
                    } else if ("DM01-06_2".equals(jiazs.get(i).getRelation())) {
                        history.setCHILDRENHISTORY(jiazs.get(i).getMedicalhistory());
                        history.setCHILDRENHISTORY_OTHER(jiazs.get(i).getReg0());
                    }
                    history.setIDCARD(data.getCardid());
                    if (i == jiazs.size() - 1) {
                        mFdbm.save(history);
                    }
                }

            }
        }


        List<ARCHIVE_ENVIRONMENT> aes = mFdbm.findAllByWhere(ARCHIVE_ENVIRONMENT.class,
                "IDCARD = '" + data.getCardid() + "'");
        if (aes.size() > 0) {
            for (ARCHIVE_ENVIRONMENT environment : aes) {
                mFdbm.delete(environment);
            }
        }

        ARCHIVE_ENVIRONMENT environment = new ARCHIVE_ENVIRONMENT();
        environment.setBLOWMEASURE(data.getOutWind());
        environment.setTOILET(data.getHastoilet());
        environment.setDRINKWATER(data.getWater());
        environment.setFUELTYPE(data.getFuel());
        environment.setLIVESTOCKRAIL(data.getFowlType());
        environment.setIDCARD(data.getCardid());
        mFdbm.save(environment);

        userInfo.setIS_UPDATE("N");
        return userInfo;
    }

    /**
     * 民族
     *
     * @param
     * @return
     * @author 王婷婷
     * @date 2017年7月27日 下午2:43:30
     */
    private String minzuName(String nationData) {
        // 1:一般人群，2：儿童，3：孕产妇，4：老年人，5：重精神病，6：高血压，7：糖尿病，8：冠心病，9：脑卒中 10：残疾人
        // 默认值1
        String nationName = "";
        if (!TextUtils.isEmpty(nationData)) {
            List<BD_DD_INFO> minzuInfos = mFdbm.findAllByWhereInInfoDB(BD_DD_INFO.class,
                    "ID = " + "'" + nationData + "'");
            if (minzuInfos.size() > 0) {
                nationName = minzuInfos.get(0).getDATAINFO();
            } else {
                nationName = "";
            }
        }

        return nationName;
    }

    /**
     * 人群分类
     *
     * @param data
     * @return
     * @date 2017年7月27日 下午2:43:15
     */
    private String calcPopulation(WebServiceData data) {
        // 1:一般人群，2：儿童，3：孕产妇，4：老年人，5：重精神病，6：高血压，7：糖尿病，8：冠心病，9：脑卒中 10：残疾人
        // 默认值1
        String population = "";
        if (!TextUtils.isEmpty(data.getIset()) && ("1".equals(data.getIset()))) {
            population += "2,";
        }
        if (!TextUtils.isEmpty(data.getIsfn()) && ("1".equals(data.getIsfn()))) {
            population += "3,";
        }
        if (!TextUtils.isEmpty(data.getIsjsb()) && ("1".equals(data.getIsjsb()))) {
            population += "5,";
        }
        if (!TextUtils.isEmpty(data.getIsgxy()) && ("1".equals(data.getIsgxy()))) {
            population += "6,";
        }
        if (!TextUtils.isEmpty(data.getIstnb()) && ("1".equals(data.getIstnb()))) {
            population += "7,";
        }
        if (!TextUtils.isEmpty(data.getIsgxb()) && ("1".equals(data.getIsgxb()))) {
            population += "8,";
        }
        if (!TextUtils.isEmpty(data.getIsncz()) && ("1".equals(data.getIsncz()))) {
            population += "9,";
        }
        if (!TextUtils.isEmpty(data.getIscjr()) && ("1".equals(data.getIscjr()))) {
            population += "10";
        }
        if ("".equals(population)) {
            population = "1";
        } else {
            if (",".equals(population.substring(population.length() - 1))) {
                population = population.substring(0, population.length() - 1);
            }
        }
        return population;
    }

    @Override
    public void start(String message) {
        if (mLinstener != null) {
            mLinstener.start(message);
        }
    }

    @Override
    public void onSynchronize(String message, int syncCount, int dataSize) {
        if (mLinstener != null) {
            mLinstener.onSynchronize(message, syncCount, mDataSize);
        }
    }

    @Override
    public void complete(String message) {
        if (mLinstener != null) {
            mLinstener.complete(message);
        }
    }

    @Override
    public void onError(String message) {
        if (mLinstener != null) {
            mLinstener.onError(message);
        }
    }

    @Override
    public void onUpload() {
        // TODO Auto-generated method stub

    }


    /**
     * 删除以前的药物数据
     */
    private void deleteOldDrugData(String idcard) {
        List<CD_DRUGCONDITION> drugList = NovaApplication.fdbmanger.findAllByWhere(CD_DRUGCONDITION.class,
                "IDCARD = '" + idcard + "' and TYPE='1'");
        for (CD_DRUGCONDITION drug : drugList) {
            if (drug != null) {
                NovaApplication.fdbmanger.delete(drug);
            }
        }
    }

    /**
     * 保存药物数据
     *
     * @param pharmacyList
     */
    private void saveDrug(List<PharmacyList> pharmacyList, String type,String idcard) {
        if (pharmacyList != null && pharmacyList.size() > 0) {
            for (PharmacyList list : pharmacyList) {
                CD_DRUGCONDITION drugcondition = new CD_DRUGCONDITION();
                drugcondition.setEVERYTIMEMG(list.getDosage());
                drugcondition.setNAME(list.getDrugName());
                drugcondition.setRES1(list.getReg2());
                drugcondition.setDAILYTIME(list.getUsage());
                drugcondition.setTYPE(type);
                drugcondition.setIDCARD(idcard);
                NovaApplication.fdbmanger.save(drugcondition);
            }
        }
    }
}
